<style scoped>
</style>

<template>
  <div>
    <el-table :data="courtTable" :header-cell-style="{'text-align':'center'}" ref="table"
              :cell-style="{'text-align':'center'}">
      <el-table-column prop="id" label="id" width="100"/>
      <el-table-column prop="categoryName" label="所属类别" width="100"/>
      <el-table-column prop="name" label="场地名称" width="100"/>
      <el-table-column prop="description" label="场地描述" width="300"/>
      <el-table-column label="图片" width="100">
        <el-tooltip slot-scope="scope" effect="light" placement="right">
          <div slot="content">
            <el-image style="width: 200px;height: 200px;overflow: hidden;" :src="scope.row.url" fit="fill"/>
          </div>
          <el-image style="width: 75px;height: 75px;overflow: hidden;border-radius: 50%" :src="scope.row.url" fit="fill"/>
        </el-tooltip>
      </el-table-column>
      <el-table-column prop="isEnable" label="场地状态" width="200">
        <el-switch slot-scope="scope" v-model="scope.row.isEnable"
                   @change="isEnableSwitchUpdate(scope.row.id,scope.row.isEnable)"
                   :active-value="1" :inactive-value="0" active-text="启用" inactive-text="禁用"/>
      </el-table-column>
      <el-table-column prop="price" label="租价" width="100"/>
      <el-table-column prop="sort" label="序号" width="100"/>
      <el-table-column prop="created" label="创建时间" width="100"/>
      <el-table-column prop="updated" label="更新时间" width="100"/>
      <el-table-column label="操作" width="250">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-search" @click="dataDrawerOpen(scope.row)">数据修改</el-button>
          <el-popover width="250" placement="right" :ref="'deleteBy'+scope.row.id">
            <p style="text-align: center">确认删除：{{ scope.row.username }}？</p>
            <p style="text-align: center">(将滑动条移至右侧以解锁“确认”)</p>
            <el-slider style="width: 100px;margin: 0 auto" v-model="deleteLine" @change="deletePopoverMaxLine($event)"
                       :show-tooltip="false"/>
            <div style="text-align: center">
              <el-button :disabled="confirmDelete" type="danger" @click="deletePopoverUpdate(scope.row.id)">确认删除
              </el-button>
            </div>
            <el-button style="margin-left: 10px" slot="reference" type="danger" icon="el-icon-delete"
                       @click="deletePopoverOpen">删除
            </el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                   :current-page="page" :page-sizes="[5,10,20,30,40,50]" :page-size="pageSize"
                   layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>

    <el-drawer :visible.sync="dataDrawer" :title="'正在修改：'+dataEditForm.name" ref="update">
      <el-form :model="dataEditForm" :rules="dataEditRule" style="max-width: 450px" ref="updateForm">
        <el-form-item label="类别id" prop="categoryId" label-width="100px">
          <el-select v-model="dataEditForm.categoryId" placeholder="请选择">
            <el-option
                v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="场地名" prop="name" label-width="100px">
          <el-input v-model="dataEditForm.name" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="图片" prop="url" label-width="100px">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:9999/zx-resource/resources/upload/image/product"
              :show-file-list="false"
              :on-success="handleAvatarSuccess" :before-upload="handleAvatarChange">
            <img v-if="dataEditForm.url" :src="dataEditForm.url" class="avatar" alt="404">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>
        <el-form-item label="场地描述" prop="description" label-width="100px">
          <el-input v-model="dataEditForm.description" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="场地状态" label-width="100px">
          <el-switch v-model="dataEditForm.isEnable" :active-value="1" :inactive-value="0" active-text="启用"
                     inactive-text="禁用"/>
        </el-form-item>
        <el-form-item label="租价" prop="price" label-width="100px">
          <el-input v-model="dataEditForm.price" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="序号" prop="sort" label-width="100px">
          <el-input v-model="dataEditForm.sort" autocomplete="off"/>
        </el-form-item>
        <div style="text-align: center">
          <el-button type="primary" style="margin-right: 150px" @click="dataDrawerUpdate">修改</el-button>
          <el-button type="danger" @click="dataDrawerClose">取消</el-button>
        </div>
      </el-form>
    </el-drawer><!--普通数据修改栏-->
  </div>
</template>

<script>
export default {
  name: "courtList",
  data() {
    return {
      courtTable: [],
      page: parseInt(""),//当前页数
      pageSize: parseInt(""),//每页展示数
      total: parseInt(""),//最大数据量
      totalPage: parseInt(""),//最大页码
      confirmDelete: true,
      deleteLine: 0,
      dataDrawer: false,
      dataEditForm: {},
      dataEditRule: {
        categoryId: [
          {required: true, message: "请输入所属类别", trigger: "blur"},
        ],
        name: [
          {required: true, message: "请输入场地名", trigger: "blur"},
        ],
        price: [
          {required: true, message: "请输入租价", trigger: "blur"},
        ]
      },
      categoryList: [],
    }
  },
  methods: {
    //列表
    loadCourt() {
      if (isNaN(this.page)) this.page = 1;
      if (isNaN(this.pageSize)) this.pageSize = 5;
      let url = "http://localhost:9999/zx-court/court/list?pageNum=" + this.page + "&pageSize=" + this.pageSize;
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).get(url).then((response) => {
        if (response.data.state === 200) {
          this.courtTable = response.data.data.list;
          this.page = response.data.data.page;
          this.pageSize = response.data.data.pageSize;
          this.total = response.data.data.total;
          this.totalPage = response.data.data.totalPage;
        } else {
          this.$message({message: response.data.message, type: "error"})
        }
      })
    },
    loadCategory() {
      let url = "http://localhost:9999/zx-court/category/getFrontIdAndName"
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          jsonResult = jsonResult.data;
          this.categoryList = jsonResult;
        }
      })
    },

    //图片
    handleAvatarChange() {
      let data = this.qs.stringify({"imageUrl": this.dataEditForm.url})
      let url = "http://localhost:9999/zx-resource/resources/deleteImg"
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).post(url, data)
    },
    handleAvatarSuccess(response) {
      this.dataEditForm.url = response.data.url
    },

    //页码
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.loadCourt();
    },//切换每页数量
    handleCurrentChange(pageNum) {
      this.page = pageNum;
      this.loadCourt();
    },//切换页码

    //修改栏
    dataDrawerUpdate() {
      this.$refs.updateForm.validate((valid) => {
        if (valid) {
          if (this.dataEditForm.sort === null || this.dataEditForm.sort === "") {
            this.dataEditForm.sort = 1
          }
          let url = "http://localhost:9999/zx-court/court/update";
          let updateData = this.qs.stringify(this.dataEditForm)
          this.axios.create(
              {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
          ).post(url, updateData).then((response) => {
            if (response.data.state === 200) {
              this.$message({message: "数据已修改，正在刷新页面", type: "success"});
              this.loadCourt();
            } else {
              this.$message({message: response.data.message, type: "error"})
            }
          })
          this.dataDrawerClose();
        } else {
          this.$message({message: "数据尚未符合要求", type: "error"})
        }
      })

    },//确认修改窗口内容并触发closingDrawer
    dataDrawerClose() {
      this.$refs.update.closeDrawer();
    },//关闭修改侧边栏
    dataDrawerOpen(data) {
      let url = "http://localhost:9999/zx-court/court/selectDetails?id=" + data.id;
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          jsonResult = jsonResult.data;
          this.dataEditForm = jsonResult;
        } else {
          this.$message({message: "获取场地信息失败，调用本地数据", type: "warning"})
          this.dataEditForm = data
        }
      })
      this.dataDrawer = true;
    },//打开数据修改侧边栏

    //删除
    deletePopoverOpen() {
      this.deleteLine = 0;
      this.confirmDelete = true;
    },//打开Popover组件，delete
    deletePopoverUpdate(id) {
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).post("http://localhost:9999/zx-court/court/delete", this.qs.stringify({"id": id})).then((response) => {
        if (response.data.state === 200) {
          this.$message({message: "删除完毕，正在刷新页面", type: "success"});
          this.loadCourt();
        } else {
          this.$message({message: response.data.message, type: "error"})
        }
      })
      this.$refs[`deleteBy` + id].doClose();
    },//根据id执行删除并关闭对应的popover删除窗口
    deletePopoverMaxLine(index) {
      if (index !== 100) {
        this.deleteLine = 0;
      }
      this.confirmDelete = index !== 100;
    },//检查删除确认条是否拉到右侧

    //状态切换
    isEnableSwitchUpdate(id, isEnable) {
      let url = "http://localhost:9999/zx-court/court/updateIsEnableById";
      let updateData = (this.qs.stringify({"id": id, "isEnable": isEnable}))
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).post(url, updateData).then((response) => {
        if (response.data.state !== 200) {
          this.$message({message: response.data.message, type: "error"})
        }
      })
    },
  },
  mounted() {
    this.loadCourt();
    this.loadCategory()
  }
}
</script>